package com.lerays.spider.sougou.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * utils.
 * 
 * @author chenxin<chenxin619315@gmail.com>
 */
public class Utils 
{
	/**
	 * searching the specifield configuration file and
	 * 		return a Properties.
	 * 
	 * @param	file
	 * @return	Properties
	 */
	public static Properties loadConf( String file )
	{
		Properties pro = new Properties();
		
		String path = Utils.class.getProtectionDomain()
				.getCodeSource().getLocation().getFile();
		
		//String confFile = new File(path).getParentFile().getParent()+"/sougouspider/conf/"+file;
		String confFile = new File(path).getParentFile().getParent()+"/conf/"+file;
		//System.out.println(confFile);
		
		try {
			pro.load(new FileReader(confFile));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return pro;
	}
	
	/**
	 * generate specifield number of basic letters.
	 * 
	 * @param	x
	 * @return	String
	 */
	public static String getRandomXLetters( int x )
	{
		String str = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		StringBuilder sb = new StringBuilder();
		
		for ( int i = 0; i < x; i++ )
		{
			int seed = (int)(Math.random() * 10000) % str.length();
			sb.append(str.charAt(seed));
		}
		
		return sb.toString();
	}
	
	private static Map<String,String> referencesMap = new HashMap<String,String>();      
    
    static
    {      
		referencesMap.put("'","\\'");
		referencesMap.put("\"","\\\"");
		referencesMap.put("\\","\\\\");
		   
		referencesMap.put("\n","\\\n");
		referencesMap.put("\0","\\\0");
		referencesMap.put("\b","\\\b");
		referencesMap.put("\r","\\\r");
		referencesMap.put("\t","\\\t");
		referencesMap.put("\f","\\\f");
    }      
    
	/**
	 * special handler for mysql string
	 * 
	 * @param	str
	 * @return	String
	 */
	public static String getSqlString( String str )
	{
		StringBuilder sb = new StringBuilder();
		for ( int i = 0; i < str.length(); i++ )
		{
			String s = str.substring(i, i+1);
			String r = referencesMap.get(s);
			if ( r != null )
			{
				sb.append(r);
			}
			else
			{
				sb.append(s);
			}
		}
		
		return sb.toString();
	}
}
